package com.bawei.lib_common.mvi

import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bawei.lib_common.base.BaseFragment
import com.bawei.lib_common.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMviFragment<T:ViewDataBinding>:BaseFragment<T> (){
//view层
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
        updataUI()
    }

    /**
     * 声明事件接收方法
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event:CustomEvent){
        //目标页面的校验
        if(event!=null&&event.target==this::class.java.simpleName){
            handEvent(event)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }


    private fun initData(){
        lifecycleScope.launch {
            sendViewIntent()
        }
    }




    private fun updataUI(){
        lifecycleScope.launch {
            //制定在Actyivity执行某一个
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUIState()
            }
        }
    }

    /**
     * 子类可以有选择性重写该方法
     */
    open suspend fun sendViewIntent(){

    }

    open suspend fun collectUIState(){

    }

    open  fun handEvent(event: CustomEvent){

    }
}